/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package homomorphism;

import org.apache.hadoop.io.WritableComparable;
import org.apache.hadoop.io.WritableComparator;
import utility.LongPair;

/**
 *
 * @author takeshi
 */
public class TotalLongPairKeyComparator extends WritableComparator {

    protected TotalLongPairKeyComparator() {
        super(LongPair.class, true);
    }

    @Override
    public int compare(WritableComparable w1, WritableComparable w2) {
        LongPair ip1 = (LongPair) w1;
        LongPair ip2 = (LongPair) w2;
        int cmp = LongPair.compare(ip1.getFirst(), ip2.getFirst());
        //   return cmp;
        if (cmp != 0) {
            return cmp;
        }
        return LongPair.compare(ip1.getSecond(), ip2.getSecond()); //abs
    }

    public int compare(LongPair ip1, LongPair ip2) {

        int cmp = LongPair.compare(ip1.getFirst(), ip2.getFirst());
        //   return cmp;
        if (cmp != 0) {
            return cmp;
        }
        return LongPair.compare(ip1.getSecond(), ip2.getSecond()); //abs
    }

    @Override
    public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) {
        /*
        try {
        ByteArrayInputStream bis = new ByteArrayInputStream(b1, s1, l1);
        long t11 = ((long) (bis.read()) << 32) + (bis.read() & 0xFFFFFFFFL);
        long t12 = ((long) (bis.read()) << 32) + (bis.read() & 0xFFFFFFFFL);
        bis.reset();
        LongPair key1 = new LongPair(t11, t12);

        bis = new ByteArrayInputStream(b1, s1, l1);
        long t21 = ((long) (bis.read()) << 32) + (bis.read() & 0xFFFFFFFFL);
        long t22 = ((long) (bis.read()) << 32) + (bis.read() & 0xFFFFFFFFL);
        bis.close();
        LongPair key2 = new LongPair(t21, t22);

        return compare(key1, key2);

        } catch (Exception e) {
        throw new RuntimeException(e);
        }

         *
         */

        int cp1 = WritableComparator.compareBytes(b1, s1, Long.SIZE / 8, b2, s2, Long.SIZE / 8);
        if (cp1 != 0) {
            return cp1;
        } else {
            cp1 = WritableComparator.compareBytes(b1, s1 + Long.SIZE / 8, Long.SIZE / 8, b2, s2 + Long.SIZE / 8, Long.SIZE / 8);
            return cp1;
        }

    }
}
